<?php
namespace Controllers;
use Models\User as Muser;
class User extends Common
{
    public function login() {
        if (isset($_SESSION['username'])) {
            header('location:/index.php?c=user&a=center');
        }
        return $this->render('User/login');
    }

    public function doLogin() {
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        if (empty($username) || empty($password)) {
            return $this->json_response(0, '用户名或者密码必须填写');
        }

//        $filename = './Database/users/' . $username . '.txt';
//        if (!file_exists($filename)) {
//            return $this->json_response(0, '用户名不存在');
//        }
//        $pwd = file_get_contents($filename);
//        if (md5($password) != $pwd) {
//            return $this->json_response(0, '密码错误');
//        }
        $user = new Muser();
        $result = $user->getUserByUsername($username);
        if (empty($result)) {
            return $this->json_response(0, '用户名不存在');
        }
        if ($result['password'] != md5($password)) {
            return $this->json_response(0, '密码错误');
        }
        $_SESSION['username'] = $username;
        return $this->json_response(1, '登录成功');
    }

    public function register() {
        return $this->render('User/register');
    }

    public function doRegister() {
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $re_password = isset($_POST['re_password']) ? $_POST['re_password'] : '';

        if (empty($username) || empty($password)) {
            return $this->json_response(0, '用户名或者密码必须填写');
        }
        if ($password != $re_password) {
            return $this->json_response(0, '两次密码不一致');
        }
        // 模拟查询数据库，看看用户名是不是被占用了
//        $filename = './Database/users/' . $username . '.txt';
//        if (file_exists($filename)) {
//            return $this->json_response(0, '用户名已存在');
//        }
//        file_put_contents($filename, md5($password));
        $user = new Muser();
        $result = $user->getUserByUsername($username);
        if($result) {
            return $this->json_response(0, '用户名已存在');
        }

        if (!$user->createUser($username, $password)) {
            return $this->json_response(0, '注册失败');
        }

        return $this->json_response(1, '注册成功');
    }

    public function logout() {
        unset($_SESSION['username']);
        header('location:/index.php?c=user&a=login');
    }



    public function center() {
        if (!isset($_SESSION['username'])) {
            header('location:/index.php?c=user&a=login');
        }
        $data = [
            'username' => $_SESSION['username']
        ];
        return $this->render('User/center', $data);
    }
}